<?php
/**
 * API 商品模块部份
 * @package
 * @version 1.0: 
 * @copyright 2003-2009 ShopEx
 * @author dreamdream
 * @license Commercial
 */
include_once(CORE_DIR.'/api/shop_api_object.php');
class api_1_0_goods extends shop_api_object {
    var $select_limited=100;
    var $app_error=array(
        'can not find the goods'=>array('no'=>'c_goods_001','debug'=>'','level'=>'warning','info'=>'找不到相应的商品','desc'=>'','debug'=>'')
    );
    /**
    * 商品部份开放的字段，包括字段类型
    * @author DreamDream
    * @return 开放的字段相关信息
    */
    function getColumns(){
        $columns=array(
            'goods_id'=>array('type'=>'int'),
            'cat_id'=>array('type'=>'int'),
            'type_id'=>array('type'=>'int'),
            'goods_type'=>array('type'=>'int'),
            'brand_name'=>array('type'=>'string','name'=>'brand_id'),
            'image_default'=>array('type'=>'string'),
            'image'=>array('type'=>'string','join'=>true),
            'udfimg'=>array('type'=>'string'),
            'brief'=>array('type'=>'string'),
            'mktprice'=>array('type'=>'string'),
            'price'=>array('type'=>'decimal'),
            'bn'=>array('type'=>'string'),
            'name'=>array('type'=>'string'),
            'marketable'=>array('type'=>'string'),
            'pdt_desc'=>array('type'=>'string'),
            'spec_desc'=>array('type'=>'string'),
            'props_name'=>array('type'=>'string','name'=>'params'),
            'category_name'=>array('type'=>'string','join'=>true),
            'goods_link'=>array('type'=>'string','join'=>true),
            'last_modify'=>array('type'=>'int'),
            'products_info'=>array('type'=>'string','join'=>true),
            'intro'=>array('type'=>'string')
        );
        return $columns;
    }

    /**
    * 设置库存
    * @param 设置库存的数据值包括Goods_id
    * @author DreamDream
    * @return 设置库存是否成功
    */
    function set_goods_bn($data){
        if(!($rs=$this->db->exec('select bn from sdb_goods where goods_id='.intval($data['goods_id'])))){
            $this->api_response('fail','data fail',$data,'can not find the goods');
        }
        unset($data['goods_id']);
        $aData=$this->varify_date_whole($data);
        $sql=$this->db->getUpdateSQL($rs,$aData);
        if(!$this->db->exec($sql)){
            $this->api_response('fail','db error',$data);
        }
        return $this->api_response('true');
    }
    /**
    * 查找商品详细信息(一次一条记录)
    * @param 查找商品的详细条件
    * @author DreamDream
    * @return 查找到的商品信息
    */
    function search_goods_detail($data){
        if(!($result['data_info']=$this->db->selectrow('select '.implode(',',$data['columns']).' from sdb_goods where goods_id='.intval($data['goods_id'])))){
            $this->api_response('fail','data fail',$data,'can not find the goods');
        }
        if($result['data_info']['brand_name']){
            $brand=$this->db->selectrow('select brand_name from sdb_brand where brand_id='.intval($result['data_info']['brand_name']));
            $result['data_info']['brand_name']=$brand['brand_name'];
        }
       
        if($result['data_info']['intro']){
           $result['data_info']['intro']=str_replace('\"','\'',$result['data_info']['intro']);
           //$result['data_info']['intro']=htmlspecialchars($result['data_info']['intro'],ENT_QUOTES);
        }
        if($result['data_info']['pdt_desc']){
            $pdt_desc=unserialize($result['data_info']['pdt_desc']);
            unset($result['data_info']['pdt_desc']);
            foreach($pdt_desc as $key=>$value){
                $result['data_info']['pdt_desc'][]=array('product_id'=>$key?$key:'','product_desc'=>$value?$value:'');
            }
        }
        if($result['data_info']['spec_desc']){
            $props=unserialize($result['data_info']['spec_desc']);
            unset($result['data_info']['spec_desc']);
            foreach($props as $key=>$value){
                    foreach($value as $s_key=>$s_value){
                        $result['data_info']['spec_desc'][$key][$s_key]['prop_id']=$key?$key:'';
                        $result['data_info']['spec_desc'][$key][$s_key]['spec_value']=$s_value['spec_value']?$s_value['spec_value']:'';
                        $result['data_info']['spec_desc'][$key][$s_key]['spec_type']=$s_value['spec_type']?$s_value['spec_type']:'';
                        $result['data_info']['spec_desc'][$key][$s_key]['spec_value_id']=$s_value['spec_value_id']?$s_value['spec_value_id']:'';
                    }
            }
           
        }
        if($data['columns_join']['category_name']){
            $category_name=$this->db->selectrow('select cat_name as category_name from sdb_goods_cat where cat_id='.intval($result['data_info']['cat_id']));
            $result['data_info']['category_name']=$category_name['category_name']?$category_name['category_name']:'';
            
        }
        if($data['columns_join']['goods_link']){
            $result['data_info']['goods_link']=$this->system->realUrl('product','index',array($data['goods_id']),null,$this->system->base_url());
        }
        if(empty($data['columns_join']['goods_link'])){
            $data['columns_join']['goods_link']='';
        }
       
        if($result['data_info']['props_name']){
            $props_name=unserialize($result['data_info']['props_name']);
            $result['data_info']['props_name']=array();
            foreach($props_name as $key=>$value){
                if(is_array($value)){
                    $result['data_info']['props_name'][]=array('name'=>key($value),'value'=>current($value)?current($value):'');
                }
            }
        }
        if($result['data_info']['image_default']){
            if($image=$this->db->selectrow('select big from sdb_gimages where gimage_id='.$result['data_info']['image_default'])){
                $result['data_info']['image_default']=$image['big']?$image['big']:'';
            }
            if($image=explode('|',$result['data_info']['image_default'])){
                if(substr($image[0],0,4)=='http'){
                    $result['data_info']['image_default']=$image[0];
                }else{
                    $result['data_info']['image_default']=$this->system->base_url().$image[0];
                }
            }

        }
        if($data['columns_join']['image']){
            $image=$this->db->selectrow('select small,big,thumbnail from sdb_gimages where goods_id='.$data['goods_id']);
            $result['data_info']['image']=array('small'=>$image['small']?$image['small']:'','big'=>$image['big']?$image['big']:'','thumbnail'=>$image['thumbnail']?$image['thumbnail']:'');
        }
        if($data['columns_join']['products_info']){
            if($products=$this->db->select('select product_id,name,bn,price,store,last_modify from sdb_products where goods_id='.intval($result['data_info']['goods_id']))){
               foreach($products as $key=>$value){
                    $result['data_info']['products_info'][$key]['product_id']=$value['product_id']?$value['product_id']:'';
                    $result['data_info']['products_info'][$key]['bn']=$value['bn']?$value['bn']:'';
                    $result['data_info']['products_info'][$key]['price']=$value['price']?$value['price']:'';
                    $result['data_info']['products_info'][$key]['store']=$value['store']?$value['store']:'';
                    $result['data_info']['products_info'][$key]['last_modify']=$value['last_modify']?$value['last_modify']:'';
               }
               unset($product_info);
            }
        }
        $this->api_response('true',false,$result);
        
    }

    function goods_wltx_exp_list($data){
        $goods_id=@explode(',',$this->system->getConf('utility.wltx'));
        $result['data_info']=$this->db->select('select goods_id,last_modify from sdb_goods where goods_id in (\''.implode('\',\'',$goods_id).'\') limit 0,30');
        $result['counts']=count($result['data_info']);
        $this->api_response('true',false,$result);
    }
    /**
    * 查找商品删除列表
    * @param 查找商品列表条件
    * @author DreamDream
    * @return 查找到的商品列表结果集
    */
    function search_deleted_goods_list($data){
        if($data['last_modify_st_time']=='0'){
            $result=$this->db->selectrow('select count(*) as counts from sdb_goods where (( last_modify>='.intval($data['last_modify_st_time']).' and last_modify<'.intval($data['last_modify_en_time']).') or (last_modify is null)) and (disabled="true" or marketable="false")');
        }else{
            $result=$this->db->selectrow('select count(*) as counts from sdb_goods where last_modify>='.intval($data['last_modify_st_time']).' and last_modify<'.intval($data['last_modify_en_time']).' and (disabled="true" or marketable="false")');
        }
        $data['deleted']=true;
        $where=$this->_filter($data);
        $result['data_info']=$this->db->select('select '.implode(',',$data['columns']).' from sdb_goods '.$where);
        $this->api_response('true',false,$result);
    }
	function set_goods_marketable_succ($data){
		if(!$data['goods_id']){
			 $this->api_response('fail','data fail',$data,'');
		}else{
			$result=$this->db->selectrow('select marketable from sdb_goods where goods_id='.$data['goods_id']);
			$this->api_response('true',false,$result);
		}
	}
    /**
    * 查找商品列表
    * @param 查找商品列表条件
    * @author DreamDream
    * @return 查找到的商品列表结果集
    */
    function search_goods_list_by_lastmodify($data){
        if($data['last_modify_st_time']=='0'){
            $result=$this->db->selectrow('select count(*) as counts from sdb_goods where (( last_modify>='.intval($data['last_modify_st_time']).' and last_modify<'.intval($data['last_modify_en_time']).') or (last_modify is null)) and disabled="false" and marketable="true"');

        }else{
            $result=$this->db->selectrow('select count(*) as counts from sdb_goods where last_modify>='.intval($data['last_modify_st_time']).' and last_modify<'.intval($data['last_modify_en_time']).' and disabled="false" and marketable="true"');
        }
    
        $where=$this->_filter($data);
        $result['data_info']=$this->db->select('select '.implode(',',$data['columns']).' from sdb_goods '.$where);
        $this->api_response('true',false,$result);
    }

    /**
    * 商品模块的过滤赛选器
    * @param 赛选条件
    * @author DreamDream
    * @return 过滤过的筛选条件
    */
    function _filter($filter){
        $where = array();
        if($filter['last_modify_st_time']=='0'){
                $where[]='((last_modify >='.intval($filter['last_modify_st_time']).' or last_modify <'.intval($filter['last_modify_en_time']).') or last_modify is null)';
        }else{
            if(isset($filter['last_modify_st_time'])){
                $where[]='last_modify >='.intval($filter['last_modify_st_time']);
            }
            if(isset($filter['last_modify_en_time'])){
                $where[]='last_modify <'.intval($filter['last_modify_en_time']);
            }
        }
        if(isset($filter['deleted'])){
            $where[]=' ( disabled="true" or marketable="false") ';
        }else{
            $where[]='disabled="false"';
            $where[]='marketable="true"';
            $where[]='goods_type!="bind"';
        }
        return parent::_filter($where,$filter);
    }
    
    /**
     * 添加销售日志
     * @param array $data
     * @return 
     */
    function create_sell_log($data){
        $orderData = $this->db->selectrow('SELECT o.member_id, m.uname,o.ship_email FROM sdb_orders o LEFT JOIN sdb_members m ON o.member_id = m.member_id WHERE o.order_id = '.$data['order_id']);
        $orderItem = $this->db->select('SELECT p.price, p.goods_id, i.product_id, p.name,p.pdt_desc, i.nums FROM sdb_order_items i LEFT JOIN sdb_products p ON p.product_id = i.product_id WHERE i.order_id = '.$data['order_id']);
        foreach( $orderItem as $iKey => $iValue ){
            $sql = 'INSERT INTO sdb_sell_logs (member_id,name,price,goods_id,product_id,product_name,pdt_desc,number,createtime) VALUES ( "'.($orderData['member_id']?$orderData['member_id']:0).'", "'.($orderData['uname']?$orderData['uname']:$orderData['ship_email']).'", "'.$iValue['price'].'", "'.$iValue['goods_id'].'", "'.$iValue['product_id'].'", "'.$iValue['name'].'", "'.$iValue['pdt_desc'].'" , "'.$iValue['nums'].'", "'.time().'" )';
            if(!$this->db->exec($sql)){
                $this->api_response('fail','db error',$data);
            }
        }
        $this->api_response('true');
    }
    
    /**
     * 更新所有商品的库存
     * @param $data
     * @return unknown_type
     */
    function update_goods_store($data){
        $sql ="SELECT goods_id , SUM(store) AS sum_store FROM sdb_products GROUP BY goods_id";
        $goods_info = $this->db->select($sql);        
        
        foreach ($goods_info as $key => $val){
            $update_str = "UPDATE sdb_goods SET store=".intval($val['sum_store'])." WHERE goods_id=".intval($val['goods_id'])." AND store!=".intval($val['sum_store']);
            if(!$this->db->exec($update_str)){
                $this->api_response('fail','db error',$data);
            }
        }
        $this->api_response('true');
    }

}